<?php
/**
 * the navigation resource loads the site tree
 * then fetches a navigation object and registers that with Digitalus Core
 * it also sets this as the default view navigation container
 *
 */
class Dig_Application_Resource_Navigation extends Zend_Application_Resource_ResourceAbstract
{
    protected $_router;
    public function init ()
    {
        $options = $this->getOptions();
        $view = $this->getBootstrap()->getResource('view');
        $siteTree = Dig_Core::getInstance()->getSiteTree();
        // fetch the root of the site tree
        $navigationObject = Dig_Navigation::factory($siteTree->getNodeByUri('/'));
        // load the front controller's router
        $frontController = $this->getBootstrap()->getResource('frontController');
        $this->_router = $frontController->getRouter();
        // add all of the CMS pages to the front controller router
        $this->_addPages($navigationObject);
        // register navigation with the cms
        $cms = Dig_Core::getInstance();
        $cms->setNavigation($navigationObject);
        $view = $this->getBootstrap()->getResource('view');
        $view->navigation()->setContainer($navigationObject);
        return $navigationObject;
    }
    protected function _addPages (Zend_Navigation_Container $container)
    {
        $pages = $container->getPages();
        if ($pages && count($pages) > 0) {
            foreach ($pages as $page) {
                if ($page instanceof Dig_Navigation_Page_Abstract) {
                    $uri = $page->getHref();
                    $requestParams = array_merge($page->getRoute(), array('navigation_node' => $page));
                    $route = new Zend_Controller_Router_Route_Static($uri, $requestParams);
                    $this->_router->addRoute($uri, $route);
                }
                // add any subpages
                $this->_addPages($page);
            }
        }
    }
}